﻿using LinqKit;
using Microsoft.Extensions.Configuration;
using OConf.Common;
using OConf.Entity;
using OConf.IBLL;
using OConf.Model;
using OConf.Model.Common;
using OConf.Service;
using System;
using System.Linq;

namespace OConf.BLL
{
    public class LoginLogBLL: ILoginLogBLL
    {
        private readonly LoginLogService _loginLogService;
        public LoginLogBLL(IConfiguration configuration)
        {
            _loginLogService = new LoginLogService(configuration);
        }

        /// <summary>
        /// 分页获取管理员登录记录列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<ReturnTableData<LoginLogPageModel>> QueryLoginLogPageList(QueryLoginLogPageListInput input)
        {
            ReturnTableData<LoginLogPageModel> result = new ReturnTableData<LoginLogPageModel>();
            ExpressionStarter<LoginLogEntity> where = PredicateBuilder.New<LoginLogEntity>(true);

            if (!string.IsNullOrEmpty(input.AccountNum))
            {
                where = where.And(w => w.AccountNum == input.AccountNum);
            }
            if (input.BeginDate.HasValue)
            {
                DateTime date = input.BeginDate.Value;
                input.BeginDate = new DateTime(date.Year, date.Month, date.Day);
                where = where.And(w => w.CreateTime >= input.BeginDate.Value);
            }
            if (input.EndDate.HasValue)
            {
                DateTime date = input.EndDate.Value.AddDays(1);
                input.EndDate = new DateTime(date.Year, date.Month, date.Day);
                where = where.And(w => w.CreateTime < input.EndDate.Value);
            }

            try
            {
                var info = _loginLogService.QueryPage(input.PageIndex, input.PageSize, where);
                result.Total = info.Total;
                result.List = info.List.Select(w => new LoginLogPageModel()
                {
                    AccountNum = w.AccountNum,
                    LoginIP = w.LoginIP,
                    CreateTime = w.CreateTime
                }).ToList();

                return ReturnDataHelper<ReturnTableData<LoginLogPageModel>>.Success("操作成功", result);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("管理后台用户分页查询,QueryPage", ex);
                return ReturnDataHelper<ReturnTableData<LoginLogPageModel>>.Exception("系统异常", null);
            }
        }

    }
}
